package com.sdx.console.rightRole.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.sdx.common.utils.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.rightRole.entity.*;
import com.sdx.console.rightRole.service.*;
import com.sdx.console.rightRole.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * RightRole 接口
 */
@RequestMapping("/rightRole/rightRole")
@Controller
public class RightRoleController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(RightRoleController.class);
    private static final String MODEL = "/rightRole/rightRole";

    private static  final String SQL = "rightRole.rightRole";


    @Resource
	private RightRoleService rightRoleService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("rightRole.rightRole.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("rightRole.rightRole.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer tenantId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        RightRole rightRole = rightRoleService.queryById(tenantId);
        view.addObject("rightRole", rightRole);
		setPageParam(view,request);
		try {
			view.addObject("rightRoleJson", JacksonUtils.toJsonString(rightRole,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("rightRole.rightRole.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("rightRole.rightRole.query")
    @ResponseBody
    public JsonResult<PageQuery> list(RightRole condtion,HttpServletRequest request)
    {
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
        PageQuery page = condtion.getPageQuery();
        rightRoleService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,RightRole rightRole,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);

    	if (isNew) {

			rightRoleService.save(rightRole);
		} else {

			rightRoleService.updateTemplate(rightRole);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("rightRole.rightRole.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)RightRole rightRole,HttpServletRequest request,String[] functionId[]
		)
    {

        return save(true,rightRole,request
		);
    }

    @PostMapping("/update.json")
    @Function("rightRole.rightRole.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  RightRole rightRole,HttpServletRequest request
		) {
		return save(false,rightRole,request
		);
    }


   
    @GetMapping("/view.json")
    @Function("rightRole.rightRole.query")
    @ResponseBody
    public JsonResult<RightRole>queryInfo(Integer tenantId) {
        RightRole rightRole = rightRoleService.queryById( tenantId);
        return  JsonResult.success(rightRole);
    }

    @PostMapping("/delete.json")
    @Function("rightRole.rightRole.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        rightRoleService.batchDelRightRole(idList);
        return JsonResult.success();
    }

    @GetMapping("/func.do")
    @Function("rightRole.rightRole.func")
    @ResponseBody
    public ModelAndView func(HttpServletRequest request,Integer tenantId,Integer roleId) {
        ModelAndView view = new ModelAndView(MODEL+"/func.html");
        Map<String,Object> param = new HashMap<>();
        param.put("tenantId",tenantId);
        param.put("roleId",roleId);
        List<RightFunction> list = rightRoleService.getSqlManager().select(SQL+".selectFunction", RightFunction.class, param);
        view.addObject("funcList", list);
        view.addObject("tenantId", tenantId);
        view.addObject("roleId", roleId);
//        RightRole rightRole = rightRoleService.queryById(tenantId);
//        view.addObject("rightRole", rightRole);
//        setPageParam(view,request);
//        try {
//           view.addObject("rightRoleJson", JacksonUtils.toJsonString(rightRole,JacksonUtils.DF1));
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
        return view;
    }

    @PostMapping("/func.json")
    @Function("rightRole.rightRole.func")
    @ResponseBody
    public JsonResult getFunc(Integer tenantId,Integer roleId,String functionIds) {
        JsonResult<Object> result = JsonResult.success();
        SQLManager sqlManager = rightRoleService.getSqlManager();
        List<String> funcIdList = Utils.strToList(functionIds,",");
        List<RightRoleFunction> list = new ArrayList<>();
        for (String functionId : funcIdList) {
            RightRoleFunction rightRoleFunction = new RightRoleFunction();
            rightRoleFunction.setFunctionId(Integer.parseInt(functionId));
            rightRoleFunction.setRoleId(roleId);
            rightRoleFunction.setTenantId(tenantId);
            list.add(rightRoleFunction);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("tenantId",tenantId);
        param.put("roleId",roleId);
        sqlManager.update(SQL+".deleteRoleFunctin",param);
        sqlManager.insertBatch(RightRoleFunction.class,list);
        return result;
    }

    @PostMapping("/getRoleFunc.json")
    @Function("rightRole.rightRole.func")
    @ResponseBody
    public JsonResult getRoleFunc(Integer tenantId,Integer roleId) {
        JsonResult<Object> result = JsonResult.success();
        Map<String,Object> param = new HashMap<>();
        param.put("tenantId",tenantId);
        param.put("roleId",roleId);
        List<BaseEntity> list = rightRoleService.getSqlManager().select(SQL+".selectRoleFunction", BaseEntity.class, param);
        result.setData(list);
        return result;
    }


    

}
